<template>
  <div class="activity-detail-container">
    <div v-loading="loading">
      <!-- 活动不存在的提示 -->
      <div v-if="notFound" class="not-found">
        <el-empty description="该活动不存在或已被删除">
          <el-button type="primary" @click="navigateToList">返回活动列表</el-button>
        </el-empty>
      </div>
      
      <!-- 活动详情 -->
      <template v-else-if="activity">
        <!-- 顶部区域 - 活动标题和操作按钮 -->
        <el-card class="page-header">
          <div class="header-content">
            <h1>{{ activity.title }}</h1>
            <div class="action-buttons">
              <!-- 管理员编辑按钮 -->
              <el-button v-if="isAdmin" type="primary" @click="showEditDialog">
                <el-icon><Edit /></el-icon> 编辑活动
              </el-button>
              <!-- 返回按钮 -->
              <el-button @click="navigateToList">
                <el-icon><Back /></el-icon> 返回列表
              </el-button>
            </div>
          </div>
        </el-card>
        
        <!-- 活动信息区域 -->
        <div class="content-area">
          <!-- 左侧: 活动信息 -->
          <el-card class="activity-info">
            <!-- 活动状态标签 -->
            <el-tag 
              :type="activity.isActive ? (isActivityInProgress ? 'success' : 'primary') : 'danger'"
              class="status-tag"
            >
              {{ getActivityStatusText() }}
            </el-tag>
            
            <!-- 活动图片 -->
            <div class="activity-image-container">
              <img 
                :src="activity.imageUrl || 'https://via.placeholder.com/800x400?text=活动封面'" 
                alt="活动图片" 
                class="activity-image"
              />
            </div>
            
            <!-- 活动基本信息 -->
            <div class="basic-info">
              <div class="info-item">
                <el-icon><Calendar /></el-icon>
                <span class="label">开始时间: </span>
                <span>{{ formatDateTime(activity.startTime) }}</span>
              </div>
              <div class="info-item">
                <el-icon><Calendar /></el-icon>
                <span class="label">结束时间: </span>
                <span>{{ formatDateTime(activity.endTime) }}</span>
              </div>
              <div class="info-item">
                <el-icon><Location /></el-icon>
                <span class="label">活动地点: </span>
                <span>{{ activity.location }}</span>
              </div>
              <div class="info-item">
                <el-icon><User /></el-icon>
                <span class="label">参与人数: </span>
                <span>{{ activity.currentParticipants }}/{{ activity.maxParticipants }}</span>
              </div>
              <div class="info-item" v-if="activity.averageRating">
                <el-icon><Star /></el-icon>
                <span class="label">平均评分: </span>
                <el-rate v-model="activity.averageRating" disabled show-score text-color="#ff9900" />
              </div>
            </div>
            
            <!-- 活动描述 -->
            <div class="description">
              <h3>活动描述</h3>
              <p>{{ activity.description }}</p>
            </div>
            
            <!-- 活动报名按钮 -->
            <div class="registration-container">
              <div v-if="activity.isActive">
                <el-button 
                  v-if="!userRegistration" 
                  type="primary" 
                  :disabled="activity.currentParticipants >= activity.maxParticipants || !isUpcoming"
                  @click="handleRegister"
                  :loading="registerLoading"
                  class="register-button"
                >
                  {{ activity.currentParticipants >= activity.maxParticipants ? '名额已满' : isUpcoming ? '立即报名' : '报名已截止' }}
                </el-button>
                <div v-else class="already-registered">
                  <el-tag type="success" size="large">您已报名此活动</el-tag>
                  <el-button 
                    v-if="isUpcoming" 
                    type="danger" 
                    @click="handleCancelRegistration"
                    :loading="cancelLoading"
                  >
                    取消报名
                  </el-button>
                </div>
              </div>
              <el-tag v-else type="danger" size="large">此活动已取消</el-tag>
            </div>
          </el-card>
          
          <!-- 右侧: 活动反馈 -->
          <el-card class="feedback-section">
            <template #header>
              <div class="feedback-header">
                <span>活动评价</span>
                <!-- 登记参加按钮 - 仅管理员可见 -->
                <el-button v-if="isAdmin && userRegistration && !userRegistration.attended" 
                  type="success" size="small" @click="markAsAttended">
                  标记为已参加
                </el-button>
                <!-- 提交评价按钮 - 仅已参加的用户可见 -->
                <el-button v-if="userRegistration && userRegistration.attended && !userHasFeedback" 
                  type="primary" size="small" @click="showFeedbackDialog">
                  提交评价
                </el-button>
              </div>
            </template>
            
            <div v-loading="feedbacksLoading">
              <!-- 无评价提示 -->
              <div v-if="feedbacks.length === 0" class="empty-feedbacks">
                <el-empty description="暂无评价" />
              </div>
              
              <!-- 评价列表 -->
              <div v-else class="feedbacks-list">
                <div v-for="feedback in feedbacks" :key="feedback.id" class="feedback-item">
                  <div class="feedback-header">
                    <div class="user-info">
                      <img class="avatar" :src="feedback.userAvatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" />
                      <span class="username">{{ feedback.userName }}</span>
                    </div>
                    <div class="rating">
                      <el-rate v-model="feedback.rating" disabled text-color="#ff9900" />
                    </div>
                  </div>
                  <div class="feedback-content">
                    <p>{{ feedback.content }}</p>
                  </div>
                  <div class="feedback-time">
                    {{ formatDateTime(feedback.createdAt) }}
                  </div>
                </div>
                
                <!-- 分页 -->
                <div v-if="feedbacks.length > 0" class="pagination-container">
                  <el-pagination
                    v-model:current-page="feedbackQuery.page"
                    v-model:page-size="feedbackQuery.size"
                    :page-sizes="[5, 10, 20]"
                    :total="feedbackTotal"
                    layout="total, sizes, prev, pager, next"
                    background
                    @size-change="handleFeedbackSizeChange"
                    @current-change="handleFeedbackPageChange"
                  />
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </template>
    </div>
    
    <!-- 编辑活动对话框 -->
    <el-dialog v-model="editDialog.visible" title="编辑活动" width="600px">
      <el-form 
        :model="editDialog.form" 
        :rules="editDialog.rules" 
        ref="editFormRef" 
        label-width="100px"
      >
        <el-form-item label="活动标题" prop="title">
          <el-input v-model="editDialog.form.title" placeholder="请输入活动标题" />
        </el-form-item>
        <el-form-item label="活动描述" prop="description">
          <el-input v-model="editDialog.form.description" type="textarea" rows="4" placeholder="请输入活动描述" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker 
            v-model="editDialog.form.startTime" 
            type="datetime" 
            placeholder="选择开始时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker 
            v-model="editDialog.form.endTime" 
            type="datetime" 
            placeholder="选择结束时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="活动地点" prop="location">
          <el-input v-model="editDialog.form.location" placeholder="请输入活动地点" />
        </el-form-item>
        <el-form-item label="最大人数" prop="maxParticipants">
          <el-input-number v-model="editDialog.form.maxParticipants" :min="1" :max="1000" />
        </el-form-item>
        <el-form-item label="活动海报" prop="imageUrl">
          <el-input v-model="editDialog.form.imageUrl" placeholder="请输入图片URL" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitActivityEdit" :loading="editDialog.submitting">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 评价对话框 -->
    <el-dialog v-model="feedbackDialog.visible" title="提交评价" width="500px">
      <el-form 
        :model="feedbackDialog.form" 
        :rules="feedbackDialog.rules" 
        ref="feedbackFormRef" 
        label-width="80px"
      >
        <el-form-item label="评分" prop="rating">
          <el-rate 
            v-model="feedbackDialog.form.rating" 
            :colors="['#99A9BF', '#F7BA2A', '#FF9900']" 
            :texts="['很差', '较差', '一般', '良好', '优秀']" 
            show-text 
          />
        </el-form-item>
        <el-form-item label="评价内容" prop="feedback">
          <el-input 
            type="textarea" 
            v-model="feedbackDialog.form.feedback" 
            rows="4" 
            placeholder="请分享您对此活动的看法..."
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="feedbackDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitFeedback" :loading="feedbackDialog.submitting">
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Calendar, Location, User, Star, Edit, Back
} from '@element-plus/icons-vue'
import { 
  getActivityById, 
  registerForActivity, 
  cancelRegistration,
  updateActivity,
  getActivityFeedbacks,
  submitFeedback,
  markAttendance
} from '@/api/club'

const route = useRoute()
const router = useRouter()
const store = useStore()
const editFormRef = ref(null)
const feedbackFormRef = ref(null)

// 数据状态
const loading = ref(false)
const activity = ref(null)
const notFound = ref(false)
const registerLoading = ref(false)
const cancelLoading = ref(false)
const userHasFeedback = ref(false)

// 管理员状态
const isAdmin = computed(() => {
  const userRoles = store.getters.roles || []
  return userRoles.includes('ADMIN')
})

// 活动ID
const activityId = computed(() => route.params.id)

// 用户报名状态
const userRegistration = ref(null)

// 活动状态计算属性
const isUpcoming = computed(() => {
  if (!activity.value || !activity.value.startTime) return false
  const startTime = new Date(activity.value.startTime)
  return startTime > new Date()
})

const isActivityInProgress = computed(() => {
  if (!activity.value || !activity.value.startTime || !activity.value.endTime) return false
  const now = new Date()
  const startTime = new Date(activity.value.startTime)
  const endTime = new Date(activity.value.endTime)
  return now >= startTime && now <= endTime
})

// 获取活动状态文本
const getActivityStatusText = () => {
  if (!activity.value) return ''
  
  if (!activity.value.isActive) {
    return '已取消'
  }
  
  const now = new Date()
  const startTime = new Date(activity.value.startTime)
  const endTime = new Date(activity.value.endTime)
  
  if (now < startTime) {
    return '即将开始'
  } else if (now > endTime) {
    return '已结束'
  } else {
    return '进行中'
  }
}

// 编辑对话框
const editDialog = reactive({
  visible: false,
  submitting: false,
  form: {
    title: '',
    description: '',
    startTime: '',
    endTime: '',
    location: '',
    maxParticipants: 20,
    imageUrl: ''
  },
  rules: {
    title: [{ required: true, message: '请输入活动标题', trigger: 'blur' }],
    description: [{ required: true, message: '请输入活动描述', trigger: 'blur' }],
    startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
    endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
    location: [{ required: true, message: '请输入活动地点', trigger: 'blur' }],
    maxParticipants: [{ required: true, message: '请设置最大人数', trigger: 'change' }]
  }
})

// 活动评价
const feedbacks = ref([])
const feedbacksLoading = ref(false)
const feedbackTotal = ref(0)
const feedbackQuery = reactive({
  page: 1,
  size: 5
})

// 评价对话框
const feedbackDialog = reactive({
  visible: false,
  submitting: false,
  form: {
    rating: 5,
    feedback: ''
  },
  rules: {
    rating: [{ required: true, message: '请给出您的评分', trigger: 'change' }],
    feedback: [{ required: true, message: '请输入您的评价内容', trigger: 'blur' }]
  }
})

// 获取活动详情
const fetchActivityDetail = async () => {
  if (!activityId.value) return
  
  loading.value = true
  try {
    const response = await getActivityById(activityId.value)
    
    if (response && response.data) {
      activity.value = response.data
      
      // 检查用户是否已报名
      if (response.data.userRegistration) {
        userRegistration.value = response.data.userRegistration
        userHasFeedback.value = !!response.data.userRegistration.feedback
      }
    } else {
      notFound.value = true
    }
  } catch (error) {
    console.error('获取活动详情失败:', error)
    if (error.response && error.response.status === 404) {
      notFound.value = true
    } else {
      ElMessage.error('获取活动详情失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 获取活动评价
const fetchActivityFeedbacks = async () => {
  if (!activityId.value) return
  
  feedbacksLoading.value = true
  try {
    const params = {
      page: feedbackQuery.page - 1,
      size: feedbackQuery.size
    }
    
    const response = await getActivityFeedbacks(activityId.value, params)
    
    if (response && response.data) {
      feedbacks.value = response.data.content || []
      feedbackTotal.value = response.data.totalElements || 0
    }
  } catch (error) {
    console.error('获取活动评价失败:', error)
    ElMessage.error('获取活动评价失败，请稍后重试')
  } finally {
    feedbacksLoading.value = false
  }
}

// 处理评价分页大小变化
const handleFeedbackSizeChange = (size) => {
  feedbackQuery.size = size
  fetchActivityFeedbacks()
}

// 处理评价页码变化
const handleFeedbackPageChange = (page) => {
  feedbackQuery.page = page
  fetchActivityFeedbacks()
}

// 导航到活动列表
const navigateToList = () => {
  router.push('/club/list')
}

// 处理活动报名
const handleRegister = async () => {
  registerLoading.value = true
  try {
    await registerForActivity(activityId.value)
    ElMessage.success('报名成功')
    
    // 刷新活动信息
    await fetchActivityDetail()
  } catch (error) {
    console.error('报名失败:', error)
    ElMessage.error('报名失败: ' + (error.response?.data?.message || '请稍后重试'))
  } finally {
    registerLoading.value = false
  }
}

// 处理取消报名
const handleCancelRegistration = () => {
  if (!userRegistration.value) return
  
  ElMessageBox.confirm('确定要取消报名吗？', '取消报名', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    cancelLoading.value = true
    try {
      await cancelRegistration(userRegistration.value.id)
      ElMessage.success('已取消报名')
      
      // 刷新活动信息
      await fetchActivityDetail()
    } catch (error) {
      console.error('取消报名失败:', error)
      ElMessage.error('取消报名失败: ' + (error.response?.data?.message || '请稍后重试'))
    } finally {
      cancelLoading.value = false
    }
  }).catch(() => {})
}

// 标记为已参加
const markAsAttended = async () => {
  if (!userRegistration.value) return
  
  try {
    await markAttendance(userRegistration.value.id, true)
    ElMessage.success('已标记为参加')
    
    // 刷新活动信息
    await fetchActivityDetail()
  } catch (error) {
    console.error('标记失败:', error)
    ElMessage.error('标记失败: ' + (error.response?.data?.message || '请稍后重试'))
  }
}

// 显示编辑对话框
const showEditDialog = () => {
  if (!activity.value) return
  
  // 复制当前活动数据到表单
  editDialog.form.title = activity.value.title
  editDialog.form.description = activity.value.description
  editDialog.form.startTime = activity.value.startTime
  editDialog.form.endTime = activity.value.endTime
  editDialog.form.location = activity.value.location
  editDialog.form.maxParticipants = activity.value.maxParticipants
  editDialog.form.imageUrl = activity.value.imageUrl || ''
  
  editDialog.visible = true
}

// 提交活动编辑
const submitActivityEdit = () => {
  editFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    editDialog.submitting = true
    try {
      await updateActivity(activityId.value, editDialog.form)
      ElMessage.success('活动已更新')
      editDialog.visible = false
      
      // 刷新活动信息
      await fetchActivityDetail()
    } catch (error) {
      console.error('更新活动失败:', error)
      ElMessage.error('更新活动失败: ' + (error.response?.data?.message || '请稍后重试'))
    } finally {
      editDialog.submitting = false
    }
  })
}

// 显示评价对话框
const showFeedbackDialog = () => {
  feedbackDialog.form.rating = 5
  feedbackDialog.form.feedback = ''
  feedbackDialog.visible = true
}

// 提交评价
const handleSubmitFeedback = () => {
  feedbackFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    feedbackDialog.submitting = true
    try {
      await submitFeedback(
        activityId.value,
        feedbackDialog.form.feedback,
        feedbackDialog.form.rating
      )
      
      ElMessage.success('评价提交成功')
      feedbackDialog.visible = false
      userHasFeedback.value = true
      
      // 刷新评价列表
      await fetchActivityFeedbacks()
    } catch (error) {
      console.error('提交评价失败:', error)
      ElMessage.error('提交评价失败: ' + (error.response?.data?.message || '请稍后重试'))
    } finally {
      feedbackDialog.submitting = false
    }
  })
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return '-'
  
  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 初始化
onMounted(() => {
  fetchActivityDetail()
  fetchActivityFeedbacks()
})
</script>

<style lang="scss" scoped>
.activity-detail-container {
  padding: 20px;
  
  .not-found {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 400px;
  }
  
  .page-header {
    margin-bottom: 20px;
    
    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      h1 {
        margin: 0;
        font-size: 24px;
      }
      
      .action-buttons {
        display: flex;
        gap: 10px;
      }
    }
  }
  
  .content-area {
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 20px;
    
    @media (max-width: 1024px) {
      grid-template-columns: 1fr;
    }
    
    .activity-info {
      position: relative;
      
      .status-tag {
        position: absolute;
        top: 10px;
        right: 10px;
        z-index: 1;
      }
      
      .activity-image-container {
        margin-bottom: 20px;
        
        .activity-image {
          width: 100%;
          max-height: 400px;
          object-fit: cover;
          border-radius: 8px;
        }
      }
      
      .basic-info {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
        gap: 15px;
        margin-bottom: 20px;
        
        .info-item {
          display: flex;
          align-items: center;
          
          .el-icon {
            margin-right: 5px;
            color: #409EFF;
          }
          
          .label {
            font-weight: bold;
            margin-right: 5px;
          }
        }
      }
      
      .description {
        margin-bottom: 20px;
        
        h3 {
          margin-top: 0;
          margin-bottom: 10px;
          border-left: 4px solid #409EFF;
          padding-left: 10px;
        }
        
        p {
          line-height: 1.6;
          white-space: pre-wrap;
        }
      }
      
      .registration-container {
        margin-top: 30px;
        text-align: center;
        
        .register-button {
          font-size: 16px;
          padding: 12px 30px;
        }
        
        .already-registered {
          display: flex;
          justify-content: center;
          align-items: center;
          gap: 15px;
        }
      }
    }
    
    .feedback-section {
      .feedback-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        span {
          font-size: 16px;
          font-weight: bold;
        }
      }
      
      .empty-feedbacks {
        padding: 30px 0;
      }
      
      .feedbacks-list {
        .feedback-item {
          padding: 15px 0;
          border-bottom: 1px solid #ebeef5;
          
          &:last-child {
            border-bottom: none;
          }
          
          .feedback-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
            
            .user-info {
              display: flex;
              align-items: center;
              
              .avatar {
                width: 32px;
                height: 32px;
                border-radius: 50%;
                margin-right: 10px;
              }
              
              .username {
                font-weight: bold;
              }
            }
          }
          
          .feedback-content {
            margin-bottom: 10px;
            
            p {
              margin: 0;
              line-height: 1.6;
            }
          }
          
          .feedback-time {
            font-size: 12px;
            color: #909399;
            text-align: right;
          }
        }
        
        .pagination-container {
          margin-top: 20px;
          display: flex;
          justify-content: center;
        }
      }
    }
  }
}
</style> 